#include<iostream>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<cstdio>
#include<cstring>
using namespace std;
void child_write(int file)
{
    char buffer[1024];
    int cnt=0;
    while(1)
    {
        snprintf(buffer,sizeof(buffer),"i am child,pid:%d,cnt:%d\n",getpid(),cnt++);
        write(file,buffer,strlen(buffer));
        sleep(1);
    }
}
void father_read(int file)
{
    char buffer[1024];
    while(1)
    {
        memset(buffer,0,sizeof(buffer));
        ssize_t n=read(file,buffer,sizeof(buffer)-1);//预留一个空间，因为上面写的是一个字符串的长度，并没有带\0，所以要留一个空间给\0
        if(n>0)
        {
            cout<<"child say:"<<buffer<<endl;
        }
    }
}
int main()
{
    //创建管道
    int fds[2]={0};
    int n=pipe(fds);//fds[0]为读端，fds[1]为写端
    if(n!=0)
    {
        cerr<<"pipe error"<<endl;
        return 1;
    }
    //创建子进程
    pid_t id=fork();
    if(id==0)
    {
        //child
        close(fds[0]);
        child_write(fds[1]);
        close(fds[1]);
        exit(0);
    }
    //关闭不需要的读写端，形成通信通道，父进程读，子进程写
    close(fds[1]);
    waitpid(id,nullptr,0);
    father_read(fds[0]);

    close(fds[0]);
    return 0;
}